<template>
  <div
    class="sync-form-container task-form-container"
    :class="{ 'error': error }"
    v-jloading="loading">
    <div class="sync-form">
      <el-form
        label-position="top"
        class="task-form">
        <el-form-item label="任务编码">
          <el-input v-model="form.task_code" placeholder="任务编码" :disabled="isUpdate"></el-input>
        </el-form-item>
        <el-form-item label="任务名称、描述">
          <el-input v-model="form.task_name" placeholder="任务名称"></el-input>
          <el-input v-model="form.task_remark" type="textarea" placeholder="任务描述"></el-input>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-radio-group v-model="form.task_type">
            <el-radio-button :label="1">普通任务</el-radio-button>
            <el-radio-button :label="2">定时任务</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Cron表达式" v-if="form.task_type === 2">
          <CronPicker v-model="form.task_cron" size="small" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            placeholder="任务开始时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="form.end_time"
            type="datetime"
            placeholder="任务结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="任务函数">
          <el-radio-group v-model="form.func_store" style="margin-bottom: 10px;">
            <el-radio-button :label="1">云函数</el-radio-button>
            <el-radio-button :label="2">专属函数</el-radio-button>
            <el-radio-button :label="3">任务文件</el-radio-button>
          </el-radio-group>
          <div class="lc-func-def" v-if="form.func_store !== 3">
            <div class="lc-func-node lc-func-info active">
              <div class="func-win-btn" @click="handleShowCloudFuncWin" v-if="form.func_store === 1">选择云函数</div>
              <div class="info">
                <div class="func-name func-code" v-if="funcCodeLabel" v-text="funcCodeLabel"></div>
                <div class="func-name" v-if="funcNameLabel" v-text="funcNameLabel"></div>
                <template v-if="!funcNameLabel && !funcCodeLabel">请选择/创建函数</template>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="svc-target lc-code-wrap">
        <div v-if="form.func_store === 3" class="code-file-view-tip">
          <h3>任务脚本文件</h3>
          <p>实现位置：{{ getTaskStorePath(form) }}</p>
        </div>
        <LownodeFunc
          v-else-if="form.func_store === 1"
          v-model="form.func"
          code-type="serverTask"
          key="cloud"
          :is-view="true"
        />
        <LownodeFunc
          v-else
          v-model="form.private_func"
          code-type="serverTask"
          key="private"
        />
      </div>
      <div class="error-tip-txt" v-text="error"></div>
    </div>
    <div class="demo-drawer__footer clear" v-if="!hideAction">
      <el-button type="primary" @click="ok">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import _ from 'lodash';
import { getTaskStorePath } from '../func/common.js';
import {api} from "@jzl/api";
import { $WinFuncs } from '@jzl/comps-mg'

const props = defineProps({
  saveMode: {
    type: String,
    default: 'save' // save - 保存， temp - 返回json
  },
  hideAction: {
    type: Boolean,
    default: false
  },
  taskId: [String, Number],
  task: [Object],
  type: {
    type: [Number, String],
    default: 3
  },
  appId: [String, Number],
});

const emit = defineEmits(['close', 'save', 'change']);

const DFT = {
  task_code: "",
  task_name: "",
  task_remark: "",
  type: 3,    // 1-平台， 2- 系统， 3-应用
  task_type: 1,   // 1-普通任务，2-定时任务
  task_cron: "",
  start_time: null,
  end_time: null,

  func_store: 2,
  func_id: null,
  private_func_id: null,
  func: null,
  private_func: null,
};

const form = ref(_.cloneDeep(DFT));
const loading = ref(false);
const error = ref(null);
const cronPopover = ref(false);

const isCloudFunc = computed(() => {
  let type = _.get(form.value.func, 'type');
  return type && (type === 1 || type === 2 || type === 3);
});

const funcNameLabel = computed(() => {
  let funcType = _.get(form.value, "func_store");
  if (funcType === 1) {
    return _.get(form.value, "func.func_name");
  } else {
    return _.get(form.value, "private_func.func_name");
  }
});

const funcCodeLabel = computed(() => {
  let funcType = _.get(form.value, "func_store");
  if (funcType === 1) {
    return _.get(form.value, "func.func_code");
  } else {
    return _.get(form.value, "private_func.func_code");
  }
});

const realAppId = computed(() => {
  let appId = _.get(form.value, "app_id");
  if (appId && appId > 0) return appId;
  return props.appId;
});

const isUpdate = computed(() => {
  return form.value && form.value.task_id > 0;
});

const errorTip = (tip) => {
  error.value = tip;
  loading.value = false;
};

const changeCron = (val, val1) => {
  console.log(val, val1)
  form.value.task_cron = val;
};

const init = async () => {
  error.value = null;
  loading.value = true;

  let formValue = null;

  // 修改
  if (props.taskId) {
    formValue = await api.task.getTask(props.taskId);

    if (!formValue) {
      return errorTip('修改数据不存在！');
    }
  } else if (props.task && props.task.task_code) {
    formValue = _.cloneDeep(props.task);
  } else {    // 新增
    formValue = _.cloneDeep(DFT);

    formValue.task_code = $utils.getNanoid();
    formValue.type = props.type;
    formValue.app_id = props.appId;
  }

  form.value = formValue;
  loading.value = false;
};

const handleShowCloudFuncWin = () => {
  $WinFuncs({
    appId: realAppId.value,
    onConfirm: (func) => {
      form.value.func = func;
    }
  });
};

const cancel = () => {
  emit("close");
};

const ok = async () => {
  let formValue = _.cloneDeep(form.value);
  let ret = null;

  if (!formValue.app_id || formValue.app_id <= 0) {
    if (props.appId) formValue.app_id = props.appId;
  }

  if (props.saveMode === 'temp') {
    emit('save', formValue);
  } else {
    loading.value = true;

    if (formValue.task_id) {
      ret = await api.task.update(formValue);
    } else {
      ret = await api.task.create(formValue);
    }

    if (ret) {
      emit('save', formValue);
    }

    loading.value = false;
  }
};

onMounted(() => {
  init();
});

watch(() => props.type, () => {
  init();
});

watch(() => props.task, () => {
  init();
}, { deep: true });

watch(() => props.taskId, () => {
  init();
});

watch(() => props.appId, () => {
  init();
});

watch(() => form.value, (val) => {
  if (loading.value) return;
  emit('change', val);
}, { deep: true });
</script>
